<?php
/**
 * Created by PhpStorm.
 * User: hahastein
 * Date: 2018/5/22
 * Time: 1:08
 */

namespace Api\Controller;

use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use Think\Controller;


class PayController extends Controller {

    private $options = array(
        'app_id' => 'wxeaa875ece47c486b',
        'secret' => '94deb4786bc203cb9f9c6d0968fdf4ee',
        'response_type' => 'array',
        'payment' => array(
            'merchant_id'        => '1508667791',//1468612802
            'key'                => 'CA97tt17mD2hj89spo67RQ92uGaoChao',
            'notify_url'         => 'http://delmar.bengboom.com/api/pay/notify'
        ),
        'guzzle' => array(
            'timeout' => 3.0, // 超时时间（秒）
            'verify' => false, // 关掉 SSL 认证（强烈不建议！！！）
        )
    );

    public function order(){

        header("Access-Control-Allow-Origin: *");

        $userID = I('post.userid');
        $product = I('post.product');
        $total_price = I('post.price');
        $agent_code = I('post.agent_code');


        if(empty($userID) || empty($product)){
            $this->ajaxReturn(array(
                'code' => 400,
                'msg' => '参数错误'
            ));
        }

        $user_info = M('user')->where(['id'=>$userID]);

        if(empty($user_info)){
            $this->ajaxReturn(array(
                'code' => 400,
                'msg' => '用户信息错误'
            ));
        }

        $app = new Application($this->options);
        $payment = $app->payment;

        $paySn = $this->makePaySn($userID);
        $orderSn = $this->makeOrderSn($userID);

        $attributes = array(
            'trade_type' => Order::APP,//不同点
            'body' => $product,
            'detail' => $product,
            'out_trade_no' => $orderSn,
            'total_fee' => $total_price*100,
            'notify_url' => 'http://delmar.bengboom.com/api/pay/notify',
        );

        $o = new Order($attributes);
        $result = $payment->prepare($o);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS') {
            $prepayId = $result->prepay_id;
            $codeUrl = $result->code_url;

            $appsdk = $payment->configForAppPayment($prepayId);

            $saveData = array(
                'ordersn' => $orderSn,
                'paysn' => $paySn,
                'price' => $total_price,
                'userid' => $userID,
                'agent_code' => $agent_code,
                'objectname' => $product,
                'addtime' => time(),
                'status' => 1
            );

            if($order_id = M('dm_order')->add($saveData)){
                $this->ajaxReturn(array(
                    'code' => 200,
                    'order_id' => $order_id,
                    'config' => $appsdk
                ));
            }else{
                $this->ajaxReturn(array(
                    'code' => 400,
                    'msg' => '支付失败'
                ));
            }


        }else{
            $this->ajaxReturn(array(
                'code' => 400,
                'msg' => 'sdk调用失败',
                'result' => $result
            ));
        }
    }

    /**
     * @throws \EasyWeChat\Core\Exceptions\FaultException
     */
    public function notify(){

        $wxApp = new Application($this->options);

        $payment = $wxApp->payment;
        $response = $payment->handleNotify(function ($notify, $successful) {
            if ($successful) {
                $notifyParam = json_decode($notify, true);

                $transactionId = $notifyParam['transaction_id'];        //微信支付交易号
                $out_trade_no = $notifyParam['out_trade_no'];           //系统订单号
                $total_fee = $notifyParam['total_fee'];                 //支付总金额


                if(M('dm_order')->where(array(
                    'ordersn' => $out_trade_no
                ))->save(array(
                    'status' => 3,
                    'tsn' => $transactionId,
                    'payprice' => $total_fee
                ))){
                    echo 'SUCCESS';
                    die;
                }else{
                    echo 'SUCCESS';
                    die;
                }

            } else {
                file_put_contents('/www/log/log_pay_notify_'.date('Ymd').'.txt', $notify . PHP_EOL, FILE_APPEND);
                echo 'FAIL';
                die;
            }
        });
    }

    /**
     * 生成支付单编号(两位随机 + 从2000-01-01 00:00:00 到现在的秒数+微秒+会员ID%1000)，该值会传给第三方支付接口
     * 长度 =2位 + 10位 + 3位 + 3位  = 18位
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @param $userID
     * @return string
     */
    private function makePaySn($userID)
    {
        return mt_rand(10, 99)
            . sprintf('%010d', time() - 946656000)
            . sprintf('%03d', (float)microtime() * 1000)
            . sprintf('%03d', (int)$userID % 1000);
    }

    /**
     * 订单编号生成规则，n(n>=1)个订单表对应一个支付表，
     * 生成订单编号(年取1位 + $pay_id取13位 + 第N个子订单取2位)
     * 1000个会员同一微秒提订单，重复机率为1/100
     * @param $userID
     * @return string
     */
    private function makeOrderSn($userID)
    {
        //记录生成子订单的个数，如果生成多个子订单，该值会累加
        static $num;
        if (empty($num)) {
            $num = 1;
        } else {
            $num++;
        }
        $pay_id_1 = mt_rand(1000, 9999);
        $pay_id_2 = mt_rand(1000, 9999);
        $pay_id = ($pay_id_1.$pay_id_2)+$userID+time();
        return (date('y', time()) % 9 + 1) . sprintf('%013d', $pay_id) . sprintf('%02d', $num);
    }


}